import { BrowserWindow, shell } from 'electron'
import { join } from 'path'
import { sendMsgToRender } from '../message/message'

export const allChildWindowsId = {
  svgSetting: null as number | null, //svg设置
  randomFunction: null as number | null, //随机函数
  jsonData: null as number | null, //json数据
  refinement: null as number | null, //单机精进页面
  lineIndicators: null as number | null //线体指标
}

//设置窗口id
export const setChildWindowsId = (id: number | null, key: string): boolean => {
  allChildWindowsId[key] = id
  return true
}

//查询窗口id
export const getChildWindowsId = (key: string): number => {
  return allChildWindowsId[key]
}

//开启一个全新的子窗口
export const openChildWindow = (data: any) => {
  const childWindow = new BrowserWindow({
    width: data?.width || 800,
    height: data?.height || 600,
    title: data.title,
    show: false,
    autoHideMenuBar: true,
    titleBarStyle: 'hidden',
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    }
  })

  childWindow.on('ready-to-show', () => {
    childWindow?.show()

    //发送一些初始数据
    childWindow.webContents.send('initData', {
      id: childWindow.id,
      key: data.key,
      title: data.title,
      data: data?.data
    })
  })

  childWindow.webContents.on('did-fail-load', (event, code, desc) => {
    console.error('Failed to load:', desc)
  })
  childWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  //监听关闭
  childWindow.on('closed', () => {
    setChildWindowsId(null, data.key)
  })

  if (process.env['ELECTRON_RENDERER_URL']) {
    childWindow.loadURL(`${process.env['ELECTRON_RENDERER_URL']}/childWindows`)
  } else {
    childWindow.loadFile(join(__dirname, '../renderer/index.html'), {
      hash: '/childWindows'
    })
  }

  setChildWindowsId(childWindow.id, data.key)

  sendMsgToRender('window', '已开启' + data.title + '窗口')
}
